<template>
  <div>
    <el-form inline size="small">
      <el-form-item label="起始日期">
        <el-date-picker
          v-model="flowStore.dataQuerierContent.begDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="起始日期"
          :clearable="false"
          style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="结束日期">
        <el-date-picker
          v-model="flowStore.dataQuerierContent.endDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="结束日期"
          :clearable="false"
          style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="计算粒度">
        <el-select
          v-model="flowStore.dataQuerierContent.gap"
          style="width: 80px"
        >
          <el-option :value="4" label="60分钟"></el-option>
          <el-option :value="2" label="30分钟"></el-option>
          <el-option :value="1" label="15分钟"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="建议模型">
        <el-radio-group v-model="flowStore.useExperimentPolicy">
          <el-radio-button :value="false">模型Ⅱ</el-radio-button>
          <el-radio-button :value="true">模型Ⅲ(测试)</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <div v-if="isIinvalid">
          <el-button type="danger" disabled>起止日期不正确</el-button>
        </div>
        <div v-else>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-popover placement="bottom-start" :width="150" trigger="hover">
            <template #reference>
              <el-button type="primary" link>
                <span>选择列</span>
                <el-icon><CaretBottom /></el-icon>
              </el-button>
            </template>
            <div style="padding-bottom: 8px">
              <el-button
                type="primary"
                size="small"
                link
                @click="handleSelectAll"
              >
                全选
              </el-button>
              <span>/</span>
              <el-button
                type="danger"
                size="small"
                link
                @click="handleSelectAll(false)"
              >
                清空
              </el-button>
            </div>
            <el-checkbox-group
              v-model="flowStore.dataQuerierContent.tableColumns"
              size="small"
            >
              <el-checkbox
                v-for="label in columnsAll"
                :label="label"
                style="width: 100%"
              />
            </el-checkbox-group>
          </el-popover>
        </div>
      </el-form-item>
    </el-form>
    <!-- <pre>{{ flowStore.dataQuerierContent.arrangedData }}</pre> -->
    <!-- <pre>{{ flowStore.dataQuerierContent }}</pre> -->
  </div>
</template>

<script setup>
import { h, ref, computed, onMounted, onUnmounted, nextTick } from "vue";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";
import axios from "axios";
import {
  cumulate,
  arrange,
  summary,
  policyCompute,
  stepCut,
  prearrange,
  arrangeSector,
} from "../utils";
import useFlowStore from "@/store/flow.js";
const flowStore = useFlowStore();

onMounted(() => {
  if (
    flowStore.dataQuerierContent.begDate == null ||
    flowStore.dataQuerierContent.endDate == null
  ) {
    flowStore.dataQuerierContent.begDate = dayjs()
      .subtract(1, "day")
      .format("YYYY-MM-DD");
    flowStore.dataQuerierContent.endDate = dayjs()
      .subtract(1, "day")
      .format("YYYY-MM-DD");
    flowStore.dataQuerierContent.gap = 4;
  }
});

const isIinvalid = computed(
  () =>
    // 起始时间大于结束时间
    dayjs(flowStore.dataQuerierContent.begDate).isAfter(
      flowStore.dataQuerierContent.endDate,
      "day"
    ) ||
    // 结束时间大于当前时间
    dayjs(flowStore.dataQuerierContent.endDate).isAfter(dayjs(), "day") ||
    // 结束时间大于当前时间
    dayjs(flowStore.dataQuerierContent.begDate).isAfter(dayjs(), "day")
);

const handleQuery = () => {
  let begTime =
    dayjs(flowStore.dataQuerierContent.begDate).format("YYYY-MM-DD") +
    " 04:00:00";
  let endTime = dayjs(flowStore.dataQuerierContent.endDate).isSame(
    dayjs(),
    "day"
  )
    ? dayjs().subtract(1, "hour").format("YYYY-MM-DD HH") + ":00:00"
    : dayjs(flowStore.dataQuerierContent.endDate)
        .add(1, "day")
        .format("YYYY-MM-DD") + " 04:00:00";
  doQuery({ begTime, endTime }).then((reply) => {
    let arrangedData = arrangeData(reply);
    flowStore.dataQuerierContent.arrangedData = arrangedData;
    // console.log("arrangedData", JSON.stringify(arrangedData));
  });
};

const doQuery = ({ begTime, endTime }) => {
  return new Promise((resolve, reject) => {
    axios
      .get(
        `api/flow_ntfm_get.php?begTime=${begTime}&endTime=${endTime}&tag=1&history=1`
      )
      .then((response) => {
        flowStore.dataQuerierContent.responseTime = dayjs().format(
          "YYYY-MM-DD HH:mm:ss.SSS"
        );
        flowStore.dataQuerierContent.response = response.data;
        resolve(response.data);
      })
      .catch((error) => {
        reject(error);
        console.error(error);
      });
  });
};

const arrangeData = (reply) => {
  let gap = flowStore.dataQuerierContent.gap;
  let tags = reply.tags;
  let begTime = reply.begTime;
  let rawData = reply.rawData;
  let rawSector = reply.sector;
  let rawDetails = reply.details;
  if (!rawData || rawData.length == 0) {
    ElMessage.error("未能查询到任何数据");
    return null;
  }
  let cumulatedRawData = cumulate(rawData, gap, gap);
  let queriedData = arrange(
    cumulatedRawData,
    tags,
    begTime,
    gap,
    ["airport", "type", "point"],
    "YYYY-MM-DD HH:mm:ss"
  );
  queriedData = policyCompute(queriedData, gap);
  let realSectorList = stepCut(rawSector, gap);
  let detailsList = stepCut(rawDetails, gap);
  let taggedDataList = prearrange(cumulatedRawData, tags, begTime, gap);
  let output = new Array();

  for (let i = 0; i < queriedData.length; i++) {
    if (!detailsList[i] || !detailsList[i] == null) {
      break;
    }
    let computingOption =
      detailsList[i].direction.ZUUU +
      detailsList[i].direction.ZUTF +
      (detailsList[i].activity.includes("温江") ? "WJ" : "");
    let sectorScheme = Object.keys(detailsList[i].seats).map((seatName) => {
      return {
        seatName: seatName,
        sectorCodes: detailsList[i].seats[seatName],
      };
    });
    let seatData = arrangeSector(
      taggedDataList[i].data,
      computingOption,
      sectorScheme
    );
    output.push({
      moment: queriedData[i].moment,
      timeStamp: queriedData[i].timestamp,
      flowData: queriedData[i],
      taggedData: taggedDataList[i],
      rawData: cumulatedRawData[i],
      enviromentData: detailsList[i],
      sectorCount: realSectorList[i],
      seatData,
      // computingOption,
    });
  }
  if (!output || output.length == 0) {
    ElMessage.warning(`查询到${queriedData.length}组数据中不包含历史数据`);
    return null;
  }
  ElMessage.success(`查询到${queriedData.length}组数据`);
  return output;
};

const columnsAll = ref([
  "扇区数量",
  "终端区架次",
  "双流架次",
  "天府架次",
  "绵阳架次",
  "双流起降分布",
  "天府起降分布",
  "绵阳起降分布",
  "扇区架次",
  "扇区负荷",
  "扇区模块",
  "扇区人员",
  "活动情况",
]);

const handleSelectAll = (value = true) => {
  if (value) {
    flowStore.dataQuerierContent.tableColumns = JSON.parse(
      JSON.stringify(columnsAll.value)
    );
  } else {
    flowStore.dataQuerierContent.tableColumns.length = 0;
  }
};
</script>
